package android.bluebox.view;

import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.bluebox.R;
import android.bluebox.model.AValue;
import android.bluebox.model.AValueAdapter;
import android.bluebox.model.Attribute;
import android.bluebox.model.StaticBox;
import android.bluebox.model.Tag;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class AValueListView extends Activity {

	ListView lvAValue;
	ArrayList<AValue> aValueList;
	AValueAdapter cba;

	TextView txtNumberOfAValues;
	TextView txtTitle;

	/*
	 * 0: attribute
	 * 1: tag
	 * 2: workspace
	 * 3: ie
	 */
	int typeId;
	int filterId;

	AValue selectedAValue;
	int numberOfAValues = 0;

	boolean recentView = true;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.avaluelist);

		typeId = getIntent().getExtras().getInt("typeId");
		filterId = getIntent().getExtras().getInt("filterId");

		txtNumberOfAValues = (TextView) findViewById(R.id.avl_number);
		txtTitle = (TextView) findViewById(R.id.avl_title);

		lvAValue = (ListView) findViewById(R.id.avl_list);
		cba = new AValueAdapter(this, aValueList);
		refreshAValueList();
		lvAValue.setOnItemClickListener(chooseAValue);
		registerForContextMenu(lvAValue);
	}

//	protected void onResume() {
//		super.onResume();
//		refreshAValueList();
//	}

	public void refreshAValueList() {
		aValueList = loadAValueList();
		cba.setArraylist(aValueList);
		cba.notifyDataSetChanged();
		lvAValue.setAdapter(cba);
	}

	public ArrayList<AValue> loadAValueList() {
		StaticBox.dbBox.setContext(this);
		ArrayList<AValue> list = null;
		switch (typeId) {
		case 0:	// attribute
			list = StaticBox.dbBox.getAllAValues(filterId);
			Attribute attr = StaticBox.dbBox.getAttribute(filterId);
			String name = attr.getName();
			txtTitle.setText(name);
			numberOfAValues = (int) StaticBox.dbBox.getNumberOfAValues();
			break;

		case 1:	// tag
			list = StaticBox.dbBox.filterAValueByTagExceptPassword(filterId);
			txtTitle.setText("Tag: " + StaticBox.dbBox.getTag(filterId).getName());
			numberOfAValues = list.size();
			break;

		case 2:	// workspace
			list = StaticBox.dbBox.getAllAValuesExceptPassword();		
			if (!recentView) {
				for (int i = 0; i < list.size() - 1; i++) {
					int maxCount = StaticBox.dbBox.getCountWorkspaceAValue(filterId, list.get(i).getId());
					int maxJ = i;
					for (int j = i + 1; j < list.size(); j++) {
						int count = StaticBox.dbBox.getCountWorkspaceAValue(filterId, list.get(j).getId());
						if (count > maxCount) {
							maxCount = count;
							maxJ = j;
						}
					}
					if (maxJ != i) {
						AValue temp = list.get(i);
						list.set(i, list.get(maxJ));
						list.set(maxJ, temp);
					}
				}
				txtTitle.setText("Workspace: " + StaticBox.dbBox.getWorkspace(filterId).getName());
				numberOfAValues = list.size();
			} else {
				for (int i = 0; i < list.size() - 1; i++) {
					String currentDate = StaticBox.getCurrentDate();
					String savedDate = StaticBox.dbBox.getLastVisitedWorkspaceAValue(filterId, list.get(i).getId());
					long minDate = StaticBox.dateToDate(currentDate, savedDate);
					int maxJ = i;
					for (int j = i + 1; j < list.size(); j++) {
						String savedJ = StaticBox.dbBox.getLastVisitedWorkspaceAValue(filterId, list.get(j).getId());
						long dateJ = StaticBox.dateToDate(currentDate, savedJ);
						if (dateJ < minDate) {
							minDate = dateJ;
							maxJ = j;
						}
					}
					if (maxJ != i) {
						AValue temp = list.get(i);
						list.set(i, list.get(maxJ));
						list.set(maxJ, temp);
					}
				}
			}
			//			/*
			//			 * end sort list
			//			 */
			break;

			/*
			 * IE
			 */
		case 3:

			break;
		}
		txtNumberOfAValues.setText(String.valueOf(numberOfAValues));
		return list;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.layout.avaluelist_optionsmenu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		switch(item.getItemId()) {
		case R.id.avl_new:
			newAValue();
			break;

		case R.id.avl_view_recent_used:
			if (!recentView)
				recentView = true;
			refreshAValueList();
			break;

		case R.id.avl_view_most_used:
			if (recentView)
				recentView = false;
			refreshAValueList();
		}

		return true;
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo info) {
		super.onCreateContextMenu(menu, view, info);
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.layout.avaluelist_contextmenu, menu);
		menu.setHeaderTitle(aValueList.get(((AdapterView.AdapterContextMenuInfo) info).position).getName());
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {

		Intent intent;

		switch (item.getItemId()) {

		case R.id.avl_home:
			intent = new Intent(AValueListView.this, FirstView.class);
			startActivity(intent);
			break;

		case R.id.avl_edit:
			AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
			selectedAValue = aValueList.get(info.position);
			break;

		case R.id.avl_edit_name:
			editAValueName(selectedAValue);
			break;

		case R.id.avl_edit_tag:
			intent = new Intent(AValueListView.this, AValueTagListView.class);
			intent.putExtra("aValueId", selectedAValue.getId());
			startActivity(intent);
			break;

		case R.id.avl_delete:
			info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
			selectedAValue = aValueList.get(info.position);
			StaticBox.dbBox.deleteAValue(selectedAValue.getId());
			refreshAValueList();
			break;
		}
		return true;
	}

	OnItemClickListener chooseAValue = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> a, View view, int position,
				long id) {
			final AValue aValue = (AValue) lvAValue.getItemAtPosition(position);

			final CharSequence[] aValueOption = {"Send", "Send All"};

			AlertDialog.Builder builder = new AlertDialog.Builder(AValueListView.this);
			builder.setTitle(aValue.getName() + " Options");
			builder.setItems(aValueOption, new OnClickListener() {

				ArrayList<AValue> list;

				@Override
				public void onClick(DialogInterface dialog, int item) {
					switch(item) {
					case 0: // send
						list = new ArrayList<AValue>();
						list.add(aValue);
						StaticBox.netBox.sendMessage(StaticBox.netBox.SENDMESSAGE, StaticBox.netBox.MISC, list);
						break;

					case 1: // send all
						if (typeId == 1) {
							StaticBox.netBox.sendMessage(StaticBox.netBox.SENDMESSAGE,
									StaticBox.dbBox.getTag(filterId).getName(), 
									aValueList);
						} else {
							final ArrayList<Tag> list = StaticBox.dbBox.getAValueTagList(aValue.getId());
							final CharSequence[] listTag = new CharSequence[list.size()];
							
							for (int i = 0; i < list.size(); i++) {
								listTag[i] = list.get(i).getName();
							}
							
							AlertDialog.Builder builder = new AlertDialog.Builder(AValueListView.this);
							builder.setTitle("Tag list");
							builder.setItems(listTag, new android.content.DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog, int item) {
									StaticBox.netBox.sendMessage(StaticBox.netBox.SENDMESSAGE, (String) listTag[item],
											StaticBox.dbBox.filterAValueByTag(list.get(item).getId()));
								}
							});
							builder.create().show();
						}
						break;
					}
				}
			});
			AlertDialog dialog = builder.create();
			dialog.show();
		}
	};

	public void newAValue() {
		AlertDialog.Builder alert = new AlertDialog.Builder(this);
		alert.setTitle("New atribute value");
		alert.setMessage("value");

		// Set an EditText view to get user Input
		final EditText edtName = new EditText(this);
		edtName.setText("");
		alert.setView(edtName);

		alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int button) {
				String newName = edtName.getText().toString().trim(); 
				if (newName.length() > 0 && StaticBox.dbBox.getAValue(newName) == null) {
					AValue aValue = new AValue();
					aValue.setName(newName);
					aValue.setAttrId(filterId);
					StaticBox.dbBox.insertAValue(aValue);
					refreshAValueList();
				} else {
					Toast.makeText(getBaseContext(), "Fail create identity", Toast.LENGTH_SHORT).show();
				}
			}
		});

		alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int button) {
			}
		});
		alert.show();
	}

	public void changeAValueName(AValue aValue, String newName) {
		aValue.setName(newName);
		StaticBox.dbBox.updateAValue(aValue);
		refreshAValueList();
	}

	public void editAValueName(final AValue aValue) {
		AlertDialog.Builder alert = new AlertDialog.Builder(this);
		alert.setTitle("Edit atribute value");
		alert.setMessage("value");

		// Set an EditText view to get user Input
		final EditText edtName = new EditText(this);
		edtName.setText(aValue.getName());
		alert.setView(edtName);

		alert.setPositiveButton("Change", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int button) {
				String newName = edtName.getText().toString().trim(); 
				if (newName.length() > 0) {
					changeAValueName(aValue, newName);
					refreshAValueList();
				} else {
					Toast.makeText(getBaseContext(), "Fail create identity", Toast.LENGTH_SHORT).show();
				}
			}
		});

		alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int button) {
			}
		});
		alert.show();
	}
}